package com.link.base.base.order.controller;

import com.link.base.sms.model.Temparameter;
import com.link.base.user.model.CoreUser;
import com.link.base.base.order.model.PayRecord;
import com.link.base.base.order.model.SaleOrder;
import com.link.base.base.order.service.PayRecordService;
import com.link.base.base.order.service.SaleOrderService;
import com.link.base.base.sms.service.PushSmsService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.DateUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author unknown
 * @date unknown
 * @comments 支付记录
 */
@Controller
@RequestMapping("/link/payRecord")
public class PayRecordController extends BasicController<PayRecord> {

    @Resource
    private SaleOrderService saleOrderService;

    @Resource
    private PayRecordService payRecordService;

    @Resource
    private PushSmsService pushSmsService;

    @Override
    public BasicService<PayRecord> getBasicService() throws Exception {
        return payRecordService;
    }

    /**
     * 新建或更新一条记录
     */
    @Override
    @RequestMapping(value = "/upsert")
    @ResponseBody
    public Map<String, Object> upsert(@JsonParam PayRecord entity, HttpSession session,
                                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            beforUpsert(entity, request);
            checkData(entity, request);
            String base = "base";
            if (!getBasicService().isInsertFlag(entity) && !checkExistDataCache(base, session, entity)) {
                throw new ServiceException("PUBLIC-002");
            }

            entity.setPayDate(DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
            entity.setPayStatus("FINISHED");
            getBasicService().upsert(entity);
            afterUpsert(entity, request);
            //审计追踪新建记录
            PayRecord newEntry = getBasicService().queryById(entity);
            result.put("newRow", newEntry);
            result.put("success", true);
        } catch (BasicServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getDetailMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 覆盖原有的insert接口，让其调用upsert接口。否则没有限制，可随意刷数据
     *
     * @author huanglongjian
     * @date 2020-01-03 10:26
     */
    @Override
    @RequestMapping(value = "/insert")
    @ResponseBody
    public Map<String, Object> insert(@JsonParam PayRecord entity, HttpSession session,
                                      HttpServletRequest request, HttpServletResponse response) {
        return this.upsert(entity, session, request, response);
    }

    @Override
    public void beforUpsert(PayRecord entity, HttpServletRequest request) throws Exception {
        SaleOrder saleOrder = saleOrderService.queryOneById(entity.getOrderId());
        String payStatus = "AlreadyPaid";
        //attr1暂存客户id
        entity.setAttrAcctId(saleOrder.getAcctId());
        if (payStatus.equals(saleOrder.getPayStatus())) {
            throw new ServiceException("ORDER-084");
        }
    }

    /**
     * 一条支付记录的变更影响对应订单的状态
     */
    public void afterUpsert(PayRecord entity, HttpServletRequest request) throws Exception {
        saleOrderService.orderStatusUpdateByPayRecord(entity);
        //当状态为已支付时，触发【场景通知】消息发送
        String finishedStr = "FINISHED";
        if (StringUtils.equals(finishedStr, entity.getPayStatus())) {
            CoreUser user = UserUtil.getUser();
            //构建参数对象
            Temparameter temparameter = new Temparameter();
            temparameter.setCorpid(user.getLoginCorpId());
            pushSmsService.sceneNotificationSendSms(entity.getAttrAcctId(), temparameter, entity.getOrderId(), "OrderPaid");
        }
    }
}
